package activator;

import java.util.Dictionary;

import library.service.LibraryService;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.log.LogService;

import service.impl.TechLibraryServiceImpl;

public class TechLibraryImplementorActivator implements BundleActivator {

	// --- Members -------------------------------------------------------------
	private BundleContext bundleContext;
	private ServiceRegistration libraryServiceRegistration;

	// log stuff
	private ServiceReference logServiceReference;
	private LogService logger;

	// --- Getters, Setters ----------------------------------------------------
	public void setBundleContext(BundleContext bundleContext) {
		this.bundleContext = bundleContext;
	}

	// --- Implementation of BundleActivator interface -------------------------
	public void start(BundleContext bundleContext) throws Exception {
		// set BundleContext
		setBundleContext(bundleContext);

		// set LogService
		setLogService();

		// load serviceProperties
		Dictionary serviceProperties = ServicePropertiesProvider
				.getServiceProperties();

		// register library service
		libraryServiceRegistration = bundleContext.registerService(
				LibraryService.class.getName(), new TechLibraryServiceImpl(),
				serviceProperties);

		// throw log message
		logger.log(LogService.LOG_INFO, "Technical LibraryService REGISTERED");
	}

	public void stop(BundleContext context) throws Exception {
		// libraryServiceRegistration clean up
		if (libraryServiceRegistration != null) {
			libraryServiceRegistration.unregister();
			libraryServiceRegistration = null;

			logger.log(LogService.LOG_INFO,
					"Technical LibraryService UN-REGISTERED");
		}

		// logging stuff clean up
		if (logServiceReference != null) {
			bundleContext.ungetService(logServiceReference);
			logServiceReference = null;
			logger = null;
		}

		// set bundleContext to NULL
		setBundleContext(null);
	}

	// --- Auxiliary methods ---------------------------------------------------

	private void setLogService() {
		// get already registered LogService by framework
		logServiceReference = bundleContext
				.getServiceReference(LogService.class.getName());
		if (logServiceReference != null) {
			logger = (LogService) bundleContext.getService(logServiceReference);
		}
	}

}
